package com.codefish.framework.spring.core.io;

import com.codefish.framework.spring.core.utils.AssertUtils;
import com.codefish.framework.spring.core.utils.ClassUtils;
import com.codefish.framework.spring.core.utils.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/30 下午 03:15
 */
public class ClassPathResource implements Resource {
    /**
     * 传入的classpath，格式为 classpath:/foo/bar/a.txt classpath:/a.txt
     */
    private final String classPath;
    /**
     * 真正的classPath ，格式为 foo/bar/a.txt或者a.txt
     */
    private final String realClassPath;
    private final ClassLoader classLoader;
    private final String resourceName;

    public ClassPathResource(String classPath) {
        this(classPath, null);
    }

    public ClassPathResource(String classPath, ClassLoader classLoader) {
        AssertUtils.notNull(classPath, "类路径不能为空");
        this.classPath = classPath;
        this.realClassPath = StringUtils.getClassPath(classPath);
        this.classLoader = classLoader == null ? ClassUtils.getDefaultClassLoader() : classLoader;
        int lastIndex = this.realClassPath.lastIndexOf("/");
        this.resourceName = this.realClassPath.substring(lastIndex + 1);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return this.classLoader.getResourceAsStream(realClassPath);
    }



    @Override
    public String getResourceName() {
        return this.resourceName;
    }

    @Override
    public String getResourcePath() {
        return this.classPath;
    }
}
